package com.qianfeng.myymatou.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.google.gson.Gson;
import com.qianfeng.myymatou.R;
import com.qianfeng.myymatou.activity.LoginActivity;
import com.qianfeng.myymatou.activity.SearchActivity;
import com.qianfeng.myymatou.adapter.ForeignGoodsRvAdapter;
import com.qianfeng.myymatou.bean.ForeignGoodsBean;
import com.qianfeng.myymatou.bean.HotSaleBean;
import com.qianfeng.myymatou.constant.UrlString;
import com.qianfeng.myymatou.utils.LogUtils;
import com.qianfeng.myymatou.view.HotSaleView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * “特卖”界面
 */
public class SaleFragment extends Fragment {

    private static final String TAG = "SaleFragment";

    private Context mContext;
    private List<HotSaleBean.DataBean.BannersBean> mBannersList;//广告条数据源
    private List<ForeignGoodsBean.DataBean.PagePartsBean> mPagePartsBeenList;//“洋货团”数据源
    private boolean isFirstIn = true;//标记变量，是否是第一次进入界面，如果是第一次就给RecyclerView加载头部，否则不再重复加载

    private Handler mHandler = new Handler();
    private OkHttpClient mOkHttpClient;
    private Request mRequest;
    private Call mCall;

    private HotSaleView mHotSaleView;
    private RecyclerView mRvForeignGoods;//显示“洋货团”列表
    private RecyclerViewHeader mHeader;
    private ForeignGoodsRvAdapter mAdapter;
    private ImageView mIvHotSaleIcon;
    private TextView mTvHotSaleName;
    private Toolbar mTbSale;
    private PtrClassicFrameLayout mPtrFl;
    private SwipeRefreshLayout mSrf;
    private ImageView mIvSaleCart;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initData();//初始化数据
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mContext = getContext();
        isFirstIn = true;
        mBannersList = new ArrayList<>();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_sale, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //找控件
        findView(view);

        //先设置好RecyclerView的LayoutManager，确保RecyclerViewHeader在RecyclerView设置了LayoutManager之后调用
        mRvForeignGoods.setLayoutManager(new LinearLayoutManager(mContext));

        //访问数据源
        loadHotSaleData(UrlString.URL_SALE_HOT_SALE);
        loadForeignGoodsData(UrlString.URL_SALE_FOREIGN_GOODS);

        //设置点击监听
        setClickListener();
    }

    /**
     * 在布局中找到控件
     *
     * @param view 整个Fragment的View
     */
    private void findView(View view) {
        mSrf = (SwipeRefreshLayout) view.findViewById(R.id.srl);
        mTbSale = (Toolbar) view.findViewById(R.id.tb_sale);
        mRvForeignGoods = (RecyclerView) view.findViewById(R.id.rv_foreignGoods);
        mHeader = (RecyclerViewHeader) view.findViewById(R.id.rv_header);
        //初始化SwipeRefreshLayout
        initSwipeRefreshLayout();
        //初始化Toolbar
        initSaleToolbar();
        //“全球热卖”标题栏+图片展示部分 的组件
        initHotSaleWidget(view);
        //“洋货团”标题栏的组件
        initForeignGoodsWidget(view);
    }

    /**
     * 初始化SwipeRefreshLayout
     */
    private void initSwipeRefreshLayout() {
        //设置进度条颜色，参数为可变长数组，可设置多种颜色
        mSrf.setColorSchemeColors(getResources().getColor(R.color.bottomTabsSelectedColor));
        //设置进度条背景色
        mSrf.setProgressBackgroundColorSchemeColor(getResources().getColor(R.color.progressBg));

        mSrf.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (mAdapter != null) {
                            //由于url中数据会自己定时更新，故下拉刷新就重新加载数据
                            loadHotSaleData(UrlString.URL_SALE_HOT_SALE);
                            loadForeignGoodsData(UrlString.URL_SALE_FOREIGN_GOODS);
                            mAdapter.updateData();
                        }
                        mSrf.setRefreshing(false);//停止刷新
                    }
                });
            }
        });
    }

    /**
     * 初始化“特卖”Toolbar
     */
    private void initSaleToolbar() {
        mTbSale.setNavigationIcon(R.mipmap.ic_search_black);//设置导航图标
        View viewInSaleTb = LayoutInflater.from(mContext).inflate(R.layout.layout_tb_sale, null);
        mTbSale.addView(viewInSaleTb);//设置Toolbar中间的布局
        mTbSale.setOverflowIcon(getResources().getDrawable(R.mipmap.ic_menu));//设置菜单溢出图标
        mTbSale.inflateMenu(R.menu.sale_menu);//设置Toolbar的菜单
        mIvSaleCart = (ImageView) viewInSaleTb.findViewById(R.id.iv_sale_cart);//购物车图标
    }

    /**
     * 初始化“全球热卖”标题栏+图片展示部分 的组件，这部分没有监听
     */
    private void initHotSaleWidget(View view) {
        LinearLayout llHotSaleTitle = (LinearLayout) view.findViewById(R.id.head_hotSale);
        mIvHotSaleIcon = (ImageView) llHotSaleTitle.findViewById(R.id.iv_categoryIcon);
        mTvHotSaleName = (TextView) llHotSaleTitle.findViewById(R.id.tv_categoryName);
        mHotSaleView = (HotSaleView) llHotSaleTitle.findViewById(R.id.hsv);
        //设置“全球热卖”小标题的内容
        mIvHotSaleIcon.setImageResource(R.mipmap.ic_earth_red);
        mTvHotSaleName.setText(R.string.hot_sale);
    }

    /**
     * 初始化“洋货团”标题栏的组件，并对“更多”作点击监听
     */
    private void initForeignGoodsWidget(View view) {
        RelativeLayout rlForeignGoods = (RelativeLayout) view.findViewById(R.id.title_foreignGoods);
        ImageView ivForeignGoodsIcon = (ImageView) rlForeignGoods.findViewById(R.id.iv_categoryIcon);
        TextView tvForeignGoodsName = (TextView) rlForeignGoods.findViewById(R.id.tv_categoryName);
        ImageView ivToMoreIcon = (ImageView) rlForeignGoods.findViewById(R.id.iv_toMore);
        //由于“洋货团”标题栏都是本地资源，故直接在这里设置
        TextView tvToMore = (TextView) rlForeignGoods.findViewById(R.id.tv_toMore);
        ivForeignGoodsIcon.setImageResource(R.mipmap.ic_foreign_goods_red);
        tvForeignGoodsName.setText(R.string.foreign_goods);
        ivToMoreIcon.setImageResource(R.mipmap.ic_common_arrow_right_red);
        tvToMore.setText(R.string.to_more);
        //对“更多”做点击监听
        tvToMore.setOnClickListener(new SaleOnClickListener());
    }

    /**
     * 由于从url返回的json字符串并不是标准的字符串，故不能直接使用VolleyUtils封装的逻辑，
     * 所以使用OkHttp访问得到字符串后对其进行split后再用Gson解析
     */
    /**
     * 获取“全球热卖”数据源
     */
    private void loadHotSaleData(String url) {
        mOkHttpClient = new OkHttpClient();
        mRequest = new Request.Builder()
                .url(url)
                .build();
        mCall = mOkHttpClient.newCall(mRequest);
        mCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, R.string.load_error, Toast.LENGTH_SHORT).show();
                    }
                });
                LogUtils.e("error==>>" + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                LogUtils.i(TAG, "response.body().string()-->" + result);
                final String jsonResult = handleResult(result);
                LogUtils.i(TAG, "jsonResult-->" + jsonResult);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        HotSaleBean hotSaleBean = new Gson().fromJson(jsonResult, HotSaleBean.class);

                        //设置解析的数据到“全球热卖”组合控件中
                        mHotSaleView.setHotSaleData(hotSaleBean.getData().getBanners());

                        if (isFirstIn) {
                            //如果是第一次进入界面，就将设置好数据的头布局添加到RecyclerView
                            //否则每执行一次loadHotSaleData就会添加一次头部
                            mHeader.attachTo(mRvForeignGoods, true);
                            isFirstIn = false;
                        }
                    }
                });
            }
        });
    }

    /**
     * 获取“洋货团”数据源
     */
    private void loadForeignGoodsData(String url) {
        mOkHttpClient = new OkHttpClient();
        mRequest = new Request.Builder()
                .url(url)
                .build();
        mCall = mOkHttpClient.newCall(mRequest);
        mCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, R.string.load_error, Toast.LENGTH_SHORT).show();
                    }
                });
                LogUtils.e("error==>>" + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                LogUtils.i(TAG, "response.body().string()-->" + result);
                final String jsonResult = handleResult(result);
                LogUtils.i(TAG, "jsonResult-->" + jsonResult);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        ForeignGoodsBean foreignGoodsBean = new Gson().fromJson(jsonResult, ForeignGoodsBean.class);
                        LogUtils.i(TAG, "ResultCount()-->" + foreignGoodsBean.getData().getResultCount());//5
                        LogUtils.i(TAG, "PagePartsCount-->" + foreignGoodsBean.getData().getPageParts().size());//5

                        //给RecyclerView设置适配器
                        mAdapter = new ForeignGoodsRvAdapter(mContext, foreignGoodsBean.getData().getPageParts());
                        mRvForeignGoods.setAdapter(mAdapter);

                    }
                });
            }
        });
    }

    /**
     * 点击事件
     */
    private void setClickListener() {
        //Toolbar中的监听
        mTbSale.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 到搜索页面的跳转
                Toast.makeText(mContext, "点击了搜索", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(mContext, SearchActivity.class));
            }
        });//不知道NavigationIcon的id，所以直接在这里处理
        mIvSaleCart.setOnClickListener(new SaleOnClickListener());
        mTbSale.setOnMenuItemClickListener(new SaleOnMenuItemClickListener());
    }

    /**
     * 点击事件
     */
    private class SaleOnClickListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.iv_sale_cart://购物车图标
                    startActivity(new Intent(mContext, LoginActivity.class));
                    break;
                case R.id.tv_toMore://“洋货团”标题栏中的“更多”
                    //TODO 仍旧缺跳转
                    Toast.makeText(mContext, "点击了更多", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }

    /**
     * Toolbar中菜单项的点击事件
     */
    private class SaleOnMenuItemClickListener implements Toolbar.OnMenuItemClickListener{
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            //TODO 点击菜单的跳转
            switch (item.getItemId()){
                case R.id.sale_menu_message:
                    Toast.makeText(mContext, "点击了消息", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.sale_menu_keeper:
                    Toast.makeText(mContext, "点击了洋管家", Toast.LENGTH_SHORT).show();
                    break;
            }
            return true;
        }
    }

    /**
     * 处理从网络获取的字符串，变成标准的json字符串
     *
     * @param result 从网络获取的字符串
     * @return 标准的json字符串
     */
    private String handleResult(String result) {
        String[] split1 = result.split("\\(");
        String[] split2 = split1[1].split("\\)");
        return split2[0];
    }

    @Override
    public void onStop() {
        super.onStop();

        if (mCall != null) {
            mCall.cancel();//取消请求
        }
    }
}
